package com.cro.prison.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cro.prison.common.ErrorMessageMethod;
import com.cro.prison.entity.constant.BEHAVIORTYPEENUM_PRISONER;
import com.cro.prison.entity.constant.IDENTITYENUM;
import com.cro.prison.entity.constant.MESSAGETYPEENUM_CRIMINAL;
import com.cro.prison.entity.pojo.*;
import com.cro.prison.entity.vo.BehaviorVo;
import com.cro.prison.entity.vo.ErrorMessageVo;
import com.cro.prison.service.*;
import com.cro.prison.utils.Code;
import com.cro.prison.utils.DateUtils;
import com.cro.prison.utils.HttpRequestUtil;
import com.cro.prison.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Controller("web_Scoket_system")
@RequestMapping("/socket")
public class SystemController {

  @Autowired
  ThreadPoolExecutor executor;

  @Autowired
  private PrisonService prisonService;
  @Autowired
  private ErrorMessageService errorMessageService;
  @Autowired
  private DeviceService deviceService;
  @Autowired
  private UserService userService;
  @Autowired
  private DepartService departService;

  @Autowired
  private DailyBehaviorService dailyBehaviorService;


  //页面请求
  @GetMapping("/index/{userId}")
  public ModelAndView socket(@PathVariable String userId) {
    ModelAndView mav = new ModelAndView("/socket1");
    mav.addObject("userId", userId);
    return mav;
  }





  //推送数据接口
  @ResponseBody
  @PostMapping("/socket/push/{cid}")
  public Map pushToWeb(@PathVariable String cid, @RequestBody ErrorMessage message) {
/*   用不到 暂时注释 2022/12/9
    List<User> users = userService.listAll();
    List<Depart> list1 = departService.list();
    List<Device> devices = deviceService.selectAll();*/
    ErrorMessageVo messageVo = ErrorMessageMethod.formatMessage(message);
    List<Depart> departList = departService.list();
    Map<Long, Depart> departMap = departList.stream().collect(Collectors.toMap(Depart::getId, d -> d));
    messageVo = ErrorMessageMethod.formatPlace(messageVo,departMap,messageVo.getDepartId());
    Map<String, Object> result = new HashMap<>();
    errorMessageService.save(message);
    messageVo.setId(message.getId());
    //String jsonMsg = formatMessage(messageVo);
    String jsonMsg = JSON.toJSONString(messageVo);
    try {
      WebSocketServer.sendInfo(jsonMsg, cid);
      result.put("code", cid);
      result.put("msg", jsonMsg);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }

  @ResponseBody
  @PostMapping("/socket/pushToAnalyseWeb/{cid}")
  public Map pushToAnalyseWeb(@PathVariable String cid) {
    System.out.println("推送信息" + cid);
    Map<String, Object> result = new HashMap<>();
    List<Prisoner>  prisonerList = prisonService.list();
    try {
      String jsonMsg = dailyBehaviorService.getToAnalyseWeb(prisonerList);
/*      String jsonMsg = "囚犯张三，编号008，近一周情绪低迷，建议进行谈话交流";*/
      if(!StringUtils.isEmpty(jsonMsg)){
        WebSocketServer.sendInfo(jsonMsg, cid);
      }
      //WebSocketServer.sendInfo(jsonMsg, cid);
      result.put("code", cid);
      result.put("msg", jsonMsg);
    } catch (IOException e) {
      log.error(e.getMessage());
    }
    System.out.println(result);
    return result;
  }

  @GetMapping("/list")
  @ResponseBody
  public Result list() {
    List<ErrorMessage> res = errorMessageService.list();
//    List<ErrorMessageVo> list = formatMessageList(res);
    List<User> users = userService.listAll();
    List<Depart> list1 = departService.list();
    List<Device> devices = deviceService.selectAll();
    List<ErrorMessageVo> list = ErrorMessageMethod.getMessageVoList(res,users,list1,devices);
    String s = formatHistoryMessage(list);
    return new Result(Code.LOGIN_OK,s);
  }

  private String formatHistoryMessage(List<ErrorMessageVo> list){
    String historyMessage = "";
    for (ErrorMessageVo item : list) {
      String current = "";
      current = current + item.getDate()+":\n"+"类型："+item.getType()+",身份："+item.getIdentity()+"\n"+"区域："+item.getPlace()+"\n\n";
      historyMessage = historyMessage+current;
    }
    historyMessage = ""+historyMessage;
    return historyMessage;
  }
  private String formatMessage(ErrorMessageVo messageVo){
    String current = "";
    current = messageVo.getDate()+":\n"+"类型："+messageVo.getType()+",身份："+messageVo.getIdentity()+"\n"+"区域："+messageVo.getPlace()+"\n\n";
    return current;
  }

  //模拟发送异常接口
  @GetMapping("/sendRequest")
  @ResponseBody
  public Result sendRequest() {
      //HttpRequestUtil.sendPost("http://127.0.0.1:8081/api/socket/socket/push/100","type=1&identity=1&createTime=2022-11-05&description=someone fight&deviceId=1",false);
      Map<String, Object> params = new HashMap<>();
      params.put("type",1);
      params.put("identity",1);
      params.put("createTime", DateUtils.getcustomDateTime(System.currentTimeMillis()));
      params.put("description","someone fight");
      params.put("deviceId",1L);
      params.put("isValid",true);
      params.put("status",0);
      params.put("videoSrc","../../../../static/test.mp4");
      params.put("departId",128L);
      params.put("userId",1L);
      HttpRequestUtil.doPost("http://127.0.0.1:8081/socket/socket/push/100",params);
    return new Result();
  }

}
